package com.yituo.mjworld.mvc.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.yituo.mjworld.core.utils.OtherTool;
import com.yituo.mjworld.mvc.service.other.CheckSumBuilder;
import com.yituo.mjworld.mvc.service.other.SmsConfig;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 验证码服务.
 * <p>
 * 文档参考地址:
 * <p>
 * http://dev.netease.im/docs/product/%E7%9F%AD%E4%BF%A1/%E7%9F%AD%E4%BF%A1%E6%8E%A5%E5%85%A5%E7%A4%BA%E4%BE%8B
 */
@Service
public class SmsServiceImpl {


  /**
   * 测试代码
   *
   * @param args
   * @throws Exception
   */
  public static void main(String[] args) throws Exception {
    SmsServiceImpl service = new SmsServiceImpl();
    System.out.println(service.sendCode("15576075986", OtherTool.getCode()));
  }

  /**
   * 发送手机验证码
   *
   * @param mobile   欲发送的手机号
   * @param randCode 随机种子数,提供给网易云用于生成随机验证码
   * @return
   * @throws Exception
   */
  public JSONObject sendCode(String mobile, int randCode) throws Exception {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(SmsConfig.SERVER_URL);
    String curTime = String.valueOf((new Date()).getTime() / 1000L);

    /**
     * 参考计算CheckSum的java代码，在上述文档的参数列表中，有CheckSum的计算文档示例
     */
    String checkSum = CheckSumBuilder.getCheckSum(SmsConfig.APP_SECRET, randCode + "", curTime);

    // 设置请求的header
    httpPost.addHeader("AppKey", SmsConfig.APP_KEY);
    httpPost.addHeader("Nonce", randCode + "");
    httpPost.addHeader("CurTime", curTime);
    httpPost.addHeader("CheckSum", checkSum);
    httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");

    // 设置请求的的参数，requestBody参数
    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    /**
     * 1.如果是模板短信，请注意参数mobile是有s的，详细参数配置请参考“发送模板短信文档”
     * 2.参数格式是jsonArray的格式，例如 "['13888888888','13666666666']"
     * 3.params是根据你模板里面有几个参数，那里面的参数也是jsonArray格式
     */
    nvps.add(new BasicNameValuePair("templateid", SmsConfig.TEMPLATEID));
    nvps.add(new BasicNameValuePair("mobile", mobile));
    nvps.add(new BasicNameValuePair("codeLen", SmsConfig.CODELEN));

    httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));

    // 执行请求
    HttpResponse response = httpClient.execute(httpPost);
    /**
     * 1.打印执行结果，打印结果一般会200、315、403、404、413、414、500
     * 2.具体的code有问题的可以参考官网的Code状态表
     */
    JSONObject result = (JSONObject) JSONObject.parse(EntityUtils.toString(response.getEntity(), "utf-8"));
    return result;
  }
}